package com.foreknow.elmboot.service.impl;

import com.foreknow.elmboot.mapper.CartMapper;
import com.foreknow.elmboot.mapper.OrderDetailetMapper;
import com.foreknow.elmboot.mapper.OrdersMapper;
import com.foreknow.elmboot.po.Cart;
import com.foreknow.elmboot.po.OrderDetailet;
import com.foreknow.elmboot.po.Orders;
import com.foreknow.elmboot.service.CartService;
import com.foreknow.elmboot.service.OrdersService;
import com.foreknow.elmboot.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.beans.Transient;
import java.util.ArrayList;
import java.util.List;
@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private OrderDetailetMapper orderDetailetMapper;

    @Override
    @Transactional
    public int createOrders(Orders orders) {
        int orderId=0;
        Cart cart=new Cart();
        cart.setUserId(orders.getUserId());
        cart.setBusinessId(orders.getBusinessId());
        orders.setOrderDate(CommonUtil.getCurrentDate());
        try {
            List<Cart> cartList=cartMapper.listCart(cart);
            ordersMapper.saveOrders(orders);
            orderId=orders.getOrderId();
            List<OrderDetailet> list=new ArrayList<>();
            for(Cart c:cartList){
                OrderDetailet od=new OrderDetailet();
                od.setOrderId(orderId);
                od.setFoodId(c.getFoodId());
                od.setQuantity(c.getQuantity());
                list.add(od);
            }
            orderDetailetMapper.saveOrderDetailetBatch(list);
            for(Cart c:cartList){
                cartMapper.deleteCart(c);
            }



        } catch (Exception e) {
            e.printStackTrace();
        }
        return orderId;
    }

    @Override
    public Orders getOrdersById(Integer orderId) {
        Orders orders=null;
        try {
            orders=ordersMapper.getOrdersById(orderId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return orders;
    }

    @Override
    public List<Orders> listOrdersByUserId(String userId) {
        List<Orders> list=null;
        try {
            list=ordersMapper.listOrdersByUserId(userId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public int updateorderState(Integer orderId) {
        int result=0;
        try {
            result=ordersMapper.updateorderState(orderId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
